<?php
/** @noinspection PhpUnused */

namespace app\shop\model\user;

use app\shop\model\BaseModel;
use Exception;
use Throwable;

class UserMoneyLogModel extends BaseModel
{
    protected $name = 'shop_user_money_log';

    public function getCreateTimeAttr($value): bool|string
    {
        return date('Y-m-d H:i:s', $value);
    }

    /**
     * 入库前
     * @throws Throwable
     */
    public static function onBeforeInsert($model): void
    {
        $user = UserModel::where('id', $model->user_id)->lock(true)->find();
        if (!$user) {
            throw new Exception("The user can't find it");
        }
        if (!$model->memo) {
            throw new Exception('Change note cannot be blank');
        }
        $model->before = $user->money;

        $user->money += $model->money;
        $user->save();

        $model->after = $user->money;
    }

    public static function onBeforeDelete(): bool
    {
        return false;
    }

    public function getMoneyAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setMoneyAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    public function getBeforeAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setBeforeAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    public function getAfterAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setAfterAttr($value): string
    {
        return bcmul($value, 100, 2);
    }
}
